﻿(function() {


    CKEDITOR.plugins.add('imagegallery', {
        icons: 'imagegallery',

        beforeInit: function(editor) {
            editor.editImg = {}; //编辑图片
            editor.uploaderImg = {}; //上传图片
            editor.editImg.dialogId = editor.name + "-imgedit-dialog";
            editor.uploaderImg.dialogId = editor.name + "-imgupload-dialog";
            //拓展
            if (plupload) {
                plupload.FILE_COUNT_ERROR = -9001;
                plupload.addFileFilter("max_file_count", function(maxFileCount, file, cb) {
                    console.group('max_file_count事件');
                    // if (maxFileCount <= this.files.length - (this.total.uploaded + this.total.failed)) {
                    if (maxFileCount <= this.files.length) {
                        this.disableBrowse(true);
                        this.trigger('Error', {
                            code: plupload.FILE_COUNT_ERROR,
                            message: "上传文件个数超出限制",
                            file: file
                        });
                        cb(false);
                    } else {
                        cb(true);
                    }
                });
            }

        },



        _editImgRender: function() {
            var editor = this;
            var htmlStr = '<div class="ckeditor-imgedit-dialog" id="' + editor.editImg.dialogId + '">' +
                '<div class="item-cell">' +
                '<label class="lab">宽：</label>' +
                '<input type="text" size="10" name="imgw" class="ipt-text">' +
                '</div>' +
                '<div class="item-cell">' +
                '<label class="lab">高：</label>' +
                '<input type="text" size="10" name="imgh" class="ipt-text">' +
                '</div>' +
                '<div class="item-cell">' +
                '<label class="lab">描述：</label>' +
                '<input type="text" name="imgalt" class="ipt-text">' +
                '</div>' +
                '<div class="item-ratio">' +
                '<span class="btnlock J_btnlock"></span>' +
                '<span class="btnreset J_btnreset"></span>' +
                '</div>' +

                '<div class="ckeditor-imgedit-ft">' +
                '<a href="#" class="ft-btn-cancel">取消</a>' +
                '<a href="#" class="ft-btn-insert ">确认</a>' +
                '</div>' +
                '</div>';
            $(htmlStr).appendTo($("body"));
            editor.editImg.$dialog = $("#" + editor.editImg.dialogId);
            editor.editImg.$inputW = editor.editImg.$dialog.find('input[name="imgw"]');
            editor.editImg.$inputH = editor.editImg.$dialog.find('input[name="imgh"]');
            editor.editImg.$inputAlt = editor.editImg.$dialog.find('input[name="imgalt"]');
            editor.editImg.$btnCancel = editor.editImg.$dialog.find('.ft-btn-cancel');
            editor.editImg.$btnConfirm = editor.editImg.$dialog.find('.ft-btn-insert');

            editor.editImg.$btnReset = editor.editImg.$dialog.find(".J_btnreset");
            editor.editImg.$btnLock = editor.editImg.$dialog.find(".J_btnlock");


            editor.editImg.$inputW.on("keyup", function() {
                var $this = $(this);
                var imgH;
                var val = $this.val() ? parseInt($this.val()) : "";
                var element = editor.editImg.element;


                editor.editImg.$inputW.val(val);

                if (element.imgLock) {
                    //锁住那么要计算一下高度
                    if (val) {
                        imgH = Math.floor(val / element.ratio);
                    } else {
                        imgH = "";
                    }


                    editor.editImg.$inputH.val(imgH);
                }
            });

            editor.editImg.$inputH.on("keyup", function() {
                var $this = $(this);
                var imgH;
                var val = $this.val() ? parseInt($this.val()) : "";
                var element = editor.editImg.element;


                editor.editImg.$inputH.val(val);

                if (element.imgLock) {
                    //锁住那么要计算一下高度
                    if (val) {
                        imgW = Math.floor(val * element.ratio);
                    } else {
                        imgW = "";
                    }


                    editor.editImg.$inputW.val(imgW);
                }
            });



        },

        _uploadImgInit: function() {
            var editor = this;
            var htmlStr = '<div class="ckeditor-imgupload-dialog" id="' + editor.uploaderImg.dialogId + '"><ul class="imgupload-tab-hd"><li class="active"><a href="#' + editor.name + '-tabbd-localupload-container">本地上传</a></li><li><a href="#' + editor.name + '-tabbd-gallery-container">相册图片</a></li><li class="move-seat"></li></ul><div class="ckeditor-localupload-container active" id="' + editor.name + '-tabbd-localupload-container"><div class="ckeditor-uploadfile-container"><div class="ckeditor-uploadfile-hd"><div class="img-upload-info"><div class="info-txt"></div><div class="info-progress"><span class="txt"></span><span class="percentage"></span></div></div><a href="javascript:void(0);" class="img-upload-btn disabled">开始上传</a><div class="img-add-btn">添加文件</div><a href="javascript:void(0);" class="img-pause-btn">暂停上传</a></div><div class="ckeditor-uploadfile-no">暂无文件，请添加图片并上传!</div><ul class="ckeditor-uploadfile-list"></ul><div class="ckeditor-uploadfile-ft"><label class="ft-save-checkbox"><input type="checkbox" name="saveingallery" />保存到相册</label><select class="ft-gallery-sel" disabled><option value="1">默认相册</option><option value="2">相册01</option><option value="3">相册02</option></select><a href="#" class="ft-btn-insert disabled">插入</a><a href="#" class="ft-btn-cancel">关闭</a></div><div class="ckeditor-uploadfile-errortip"><i class="close"></i><div class="txt"></div></div></div></div><div class="ckeditor-gallery-container" id="' + editor.name + '-tabbd-gallery-container"><div class="ckeditor-gallery-nodata" style="display:none;">您的相册目前还没有照片,<a href="#">立马去上传</a></div><div class="ckeditor-gallery-hasdata" style="display:block;"><ul class="ckeditor-gallery-list"></ul><div class="ckeditor-gallery-ft"><select class="ft-galleryall-sel"><option value="1">默认相册</option><option value="2">相册01</option><option value="3">相册02</option></select><a href="#" class="ft-galleryall-insert disabled">插入</a><a href="#" class="ft-galleryall-cancel">取消</a></div></div></div></div>';
            $(htmlStr).appendTo($("body"));




            function toggleBrowseButton(up) {
                if (up.settings.filters.max_file_count <= up.files.length) {
                    up.disableBrowse(true);
                    up.$choiceBtn.addClass("disabled");
                } else {
                    up.disableBrowse(false);
                    up.$choiceBtn.removeClass("disabled");
                }
            }

            function toggleHanderBar(up, file, eventing) {
                switch (eventing) {
                    case "FilesAdded":
                        file.$handerBar.show();
                        if (up.settings.filters.max_file_count <= 1) {
                            file.$uploadQueuedBtn.show();
                        }
                        break;
                    case "BeforeUpload":
                        file.$handerBar.hide();
                        break;
                    case "FileUploadedSuccess":
                        file.$handerBar.hide();
                        break;
                    case "FileUploadedFail":
                        file.$handerBar.show();
                        if (up.settings.filters.max_file_count <= 1) {
                            file.$uploadQueuedBtn.show();
                        }
                        break;

                    case "UploadComplete":
                        file.$handerBar.show();
                        break;
                }
            }


            function toggleStartUpload(up, eventing) {
                if (up.settings.filters.max_file_count <= 1) return;
                switch (eventing) {
                    case "Refresh":
                    case "UploadComplete":
                        if ((up.files.length - up.total.uploaded > 0) || up.total.failed) {
                            up.$btnStartload.show().removeClass('disabled');

                        } else {
                            up.$btnStartload.addClass('disabled');
                        }
                        break;
                    case "BeforeUpload":
                        up.$btnStartload.addClass('disabled');
                        break;
                    case "Pausing":
                        up.$btnStartload.removeClass('disabled');
                        break;
                }

            }

            function toggleStopUpload(up, eventing) {
                if (up.settings.filters.max_file_count <= 1) return;
                switch (eventing) {
                    case "BeforeUpload":
                        up.$btnStopload.removeClass('disabled').show();
                        break;
                    case "UploadComplete":
                        up.$btnStopload.removeClass('disabled').hide();
                        break;
                    case "Pausing":
                        up.$btnStopload.addClass('disabled');
                        break;
                }
            }






            function preloadThumb(file, $previewPic, cb, uploader) {
                var img = new moxie.image.Image();
                var resolveUrl = moxie.core.utils.Url.resolveUrl;
                img.onload = function() {
                    this.embed($previewPic[0], {
                        // width: self.options.thumb_width,
                        // height: self.options.thumb_height,
                        width: uploader.settings.resize.width,
                        height: uploader.settings.resize.height,
                        crop: uploader.settings.resize.crop,
                        fit: true,
                        preserveHeaders: uploader.settings.resize.preserve_headers,
                        swf_url: resolveUrl(uploader.settings.flash_swf_url),
                        xap_url: resolveUrl(uploader.settings.silverlight_xap_url)
                    });
                };

                img.bind("embedded error", function(e) {
                    //不支持的预览的文件浏览器就会触发error事件,
                    //支持的浏览器会触发embedded
                    this.destroy();
                    setTimeout(function() {
                        cb.call(null, e.type)
                    }, 1); // detach, otherwise ui might hang (in SilverLight for example)
                });


                img.load(file.getSource());
            }

            function toggleInsertBtn(up) {
                if (up.$uploadUL.children().hasClass('selected')) {
                    up.$insertBtnLocal.removeClass('disabled')
                } else {
                    up.$insertBtnLocal.addClass('disabled')
                }
            }


            function toggleUploadInfo(up, eventing) {

                if (!up.settings.hasUploadInfo || !up.$uploadInfo.length) return;

                var text = '';
                console.dir(up.total.size);
                if (eventing == "UploadComplete") {

                    text = '共' + up.files.length + '张（' + plupload.formatSize(up.total.size) + '），已上传' + up.total.uploaded + '张';
                    if (up.total.failed) {
                        text += '，失败' + up.total.failed + '张,<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>';
                    }
                    up.$uploadInfo.$progress.hide();
                } else if (eventing == "BeforeUpload") {
                    up.$uploadInfo.$progress.$txt.html(up.total.percent + "%");
                    up.$uploadInfo.$progress.$percent.width(up.total.percent + "%");
                    up.$uploadInfo.$progress.show();
                } else if (eventing == "UploadProgress") {
                    up.$uploadInfo.$progress.$txt.html(up.total.percent + "%");
                    up.$uploadInfo.$progress.$percent.width(up.total.percent + "%");
                } else {
                    if (up.total.uploaded) {
                        text = '共' + up.files.length + '张（' + plupload.formatSize(up.total.size) + '），已上传' + up.total.uploaded + '张';
                        if (up.total.failed) {
                            text += '，失败' + up.total.failed + '张,<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>图片';
                        }
                    } else {
                        text = '选中' + up.files.length + '张图片，共' + plupload.formatSize(up.total.size) + '。';
                    }
                }


                if (!up.files.length) {
                    up.$uploadInfo.$infoText.html("");
                } else {

                    up.$uploadInfo.$infoText.show().html(text);
                }
            }

            function getGalleryData(params) {
                $.ajax({
                    url: opt.galleryListUrl,
                    type: 'post',
                    dataType: 'json',
                    data: params,
                    success: function(res) {
                        var strArr = [];
                        $.each(res.list, function(index, src) {
                            strArr.push('<li data-src="' + src + '"><div class="pic"><img src="' + src + '" /></div><span class="status-check"></span></li>');
                        });
                        uploader.$galleryList.html(strArr.join(""));

                    }
                })
            }



            var $dialog = $("#" + editor.uploaderImg.dialogId);
            editor.uploaderImg.$dialog = $dialog;




            var $addBtn = $dialog.find(".img-add-btn"); //添加按钮
            //设置id,方便plupload初始化        
            $addBtn.attr("id", editor.name + "-img-add-btn");






            //设置默认的参数
            var defaultConfig = {
                runtimes: 'html5,flash,silverlight,html4',
                browse_button: $addBtn.get(0), // you can pass an id...
                url: './php/upload.php',

                flash_swf_url: './js/plupload/Moxie.swf',
                silverlight_xap_url: './js/plupload/Moxie.xap',
                chunk_size: 0,
                max_retries: 0,
                multi_selection: true,
                multipart_params: {},
                delServerBtn: true,
                hasUploadInfo: true,
                inputHidden: {
                    name: "photo_url[]"
                },
                filters: {
                    max_file_count: 3,
                    prevent_duplicates: true,
                    max_file_size: '30mb',
                    mime_types: [
                        { title: "Image files", extensions: "jpg,gif,png" },
                        { title: "Zip files", extensions: "zip" }
                    ]
                },
                resize: {
                    // width: 100,
                    // height: 100,
                    // //是否裁剪图片
                    // crop: true,
                    //压缩后图片的质量，只对jpg格式的图片有效，默认为90。quality可以跟width和height一起使用，但也可以单独使用，单独使用时，压缩后图片的宽高不会变化，但由于质量降低了，所以体积也会变小
                    quality: 60,
                    //压缩后是否保留图片的元数据，true为保留，false为不保留,默认为true。删除图片的元数据能使图片的体积减小一点点
                    preserve_headers: false
                }
            }

            var opt = $.extend(true, {}, defaultConfig, editor.config.plupload);
            var uploader = editor.uploader = new plupload.Uploader(opt);









            uploader.$dialog = $dialog;

            uploader.$noFileDefault = $dialog.find(".ckeditor-uploadfile-no");
            uploader.$choiceBtn = $addBtn;
            uploader.$uploadUL = $dialog.find(".ckeditor-uploadfile-list"); //ul列表
            uploader.$btnStartload = $dialog.find(".img-upload-btn");
            uploader.$btnStopload = $dialog.find(".img-pause-btn");

            //本地上传的插入按钮和相册插入按钮
            uploader.$insertBtnLocal = $dialog.find(".ft-btn-insert");
            uploader.$insertBtnServer = $dialog.find(".ft-galleryall-insert");
            uploader.$galleryList = $dialog.find(".ckeditor-gallery-list");
            uploader.$galleryListSel = $dialog.find(".ft-galleryall-sel");

            uploader.$gallerySaveSel = $dialog.find('.ft-gallery-sel')

            //获取相册分类
            $.ajax({
                url: opt.galleryClassifyUrl,
                type: 'post',
                dataType: 'json',
                data: opt.multipart_params,
                success: function(res) {
                    var strArr = [];
                    $.each(res.list, function(index, item) {
                        strArr.push('<option value="' + item.id + '">' + item.text + '</option>');
                    });

                    uploader.$galleryListSel.html(strArr.join(""));
                    uploader.$gallerySaveSel.html(strArr.join(""));

                }
            })


            //tab 选项卡
            $dialog.find('.imgupload-tab-hd a').click(function(e) {
                e.preventDefault();
                $(this).editorTab('show');
            });

            //tab切换到相册图片
            $('a[href="#' + editor.name + '-tabbd-gallery-container"]').on('shown.bs.tab', function(e) {
                var $this = $(this);
                if (!$this.data("first")) {
                    $this.attr("data-first", true);
                    var params = {
                        galleryid: uploader.$galleryListSel.val(),
                        uid: uploader.settings.multipart_params.uid
                    }
                    getGalleryData(params);
                }
            });
            //相册图片中图片切换
            uploader.$galleryListSel.on("change", function() {
                var params = {
                    galleryid: uploader.$galleryListSel.val(),
                    uid: uploader.settings.multipart_params.uid
                }
                getGalleryData(params);

            });

            if (!!opt.hasUploadInfo) {
                uploader.$uploadInfo = $dialog.find(".img-upload-info");
                if (uploader.$uploadInfo.length) {
                    uploader.$uploadInfo.$infoText = uploader.$uploadInfo.find(".info-txt");
                    uploader.$uploadInfo.$progress = uploader.$uploadInfo.find(".info-progress");
                    uploader.$uploadInfo.$progress.$txt = uploader.$uploadInfo.$progress.children(".txt");
                    uploader.$uploadInfo.$progress.$percent = uploader.$uploadInfo.$progress.children(".percentage");
                    $(document).on("click", ".img-upload-info .retry", function(event) {
                        event.preventDefault();
                        for (var i = 0; i < uploader.files.length; i++) {
                            if (uploader.files[i].status == plupload.FAILED) {
                                uploader.files[i].status = plupload.QUEUED;
                            }
                        }
                        uploader.start();
                    });

                    $(document).on("click", ".img-upload-info .ignore", function(event) {
                        event.preventDefault();
                        console.dir("ignore 点击xxxxxxxxxxxxxx");
                        console.dir(uploader.files);

                        for (var i = 0; i < uploader.files.length; i++) {
                            if (uploader.files[i].status == plupload.FAILED) {
                                uploader.removeFile(uploader.files[i]);
                                i--;
                            }
                        }
                        console.dir(uploader.files);

                    })
                }
            }

            //本地上传图片选择
            uploader.$uploadUL.on("click", "li", function() {
                var $this = $(this);
                if ($this.hasClass('selected')) {
                    $this.removeClass('selected');
                } else {
                    $this.addClass('selected');
                }
                toggleInsertBtn(uploader);
            })

            uploader.$insertBtnLocal.on("click", function() {
                var $this = $(this);
                if ($this.hasClass('disabled')) return;
                //插入编辑器
                var arr = [];
                uploader.$uploadUL.children().each(function(index, el) {
                    var $el = $(el);
                    if ($el.hasClass('selected')) {
                        arr.push($el.data("src"));
                    }
                });
                console.dir(arr);
            });

            uploader.$insertBtnServer.on("click", function() {
                var $this = $(this);
                if ($this.hasClass('disabled')) return;
                var arr = [];
                //插入编辑器
                uploader.$galleryList.children().each(function(index, el) {
                    var $el = $(el);
                    if ($el.hasClass('selected')) {
                        arr.push($el.data("src"));
                    }
                });
                console.dir(arr);

            });

            uploader.$insertBtnLocal.on("click", function(event) {
                event.preventDefault();
                var str = "";
               
                uploader.$uploadUL.children("li").each(function(index, el) {

                    var $el = $(el);
                    var src = $el.attr("data-src");
                    var id = $el.attr("id");
                   
                    if (!!src) {
                        // str='<div class="simplebox"><p><img src="'+src+'" /></p><div class="simplebox-content"><p>Content...</p></div></div>';
                        var img = editor.document.createElement('img');
                        img.setAttributes({ 'src': src });
                        editor.insertElement(img);
                        editor.insertHtml(str);
                        
                    }
                });
                
                layer.close(editor.uploaderImg.layerIndex);

            });

            uploader.$insertBtnServer.on("click", function() {
                var $this = $(this);
                var str = "";
                if ($this.hasClass('disabled')) return;
                
                //插入编辑器
                uploader.$galleryList.children().each(function(index, el) {
                    var $el=$(el);
                    var src = $el.attr("data-src");
                    if($el.hasClass('selected')){
                        var img = editor.document.createElement('img');
                        img.setAttributes({ 'src': src });
                        editor.insertElement(img);
                        editor.insertHtml(str);
                    }
                });
                layer.close(editor.uploaderImg.layerIndex);
               
                
            });

            //相册中选择  插入按钮
            uploader.$galleryList.on("click", "li", function(e) {
                e.preventDefault();
                var $this = $(this);
                if ($this.hasClass('selected')) {
                    $this.removeClass('selected')
                } else {
                    $this.addClass('selected');
                }
                if (uploader.$galleryList.children().hasClass('selected')) {
                    uploader.$insertBtnServer.removeClass('disabled')
                } else {
                    uploader.$insertBtnServer.addClass('disabled')
                }
            });


            //多个文件上传按钮
            uploader.$btnStartload.on("click", function() {
                console.dir("btnStartload点击事件");
                var $this = $(this);
                if ($this.hasClass('disabled')) return;
                // 编辑files 对于那些
                for (var i = 0; i < uploader.files.length; i++) {
                    if (uploader.files[i].status == plupload.FAILED) {
                        uploader.files[i].status = plupload.QUEUED;
                    }
                }
                uploader.start();
                toggleStopUpload(uploader, "BeforeUpload");

            });

            uploader.$btnStopload.on("click", function() {
                console.dir("btnStopload点击事件");
                uploader.stop();
                toggleStartUpload(uploader, "Pausing");
                toggleStopUpload(uploader, "Pausing");
            });



            uploader.bind("Init", function(uploader) {
                console.group("Init事件:当Plupload初始化完成后触发监听函数参数：(uploader)");
                !!opt.initLoad && !!opt.initLoad(uploader);
            });

            uploader.bind("PostInit", function() {
                console.group("PostInit事件:当Init事件发生后触发监听函数参数：(uploader)");
            });

            uploader.bind("Browse", function(up) {
                console.group("Browse事件")
            });

            uploader.bind('FileFiltered', function(up, file) {
                console.group("FileFiltered事件");

            });


            //这里的files是指每次添加的，而不是总的
            uploader.bind('FilesAdded', function(up, files) {
                console.group("FilesAdded事件");
                plupload.each(files, function(file) {

                    var str = '<li id="' + file.id + '">' +
                        '<div class="img-wrap preview">' +
                        '<div class="preview-tip"><span>预览中...</span></div>' +
                        '<div class="preview-name"></div>' +
                        '<div class="preview-pic"></div>' +
                        '<div class="handle-bar"><span class="upbtn-del">删除</span></div>' +
                        '<p class="progressing"><span style="width:0%;"></span></p>' +
                        '<span class="error">上传失败，请重试</span>' +
                        '<span class="successing"></span>' +
                        '</div>' +
                        (opt.inputHidden ? '<input type="hidden" id="' + file.id + '" name="' + opt.inputHidden.name + '">' : '') +
                        '</li>';

                    file.$li = $(str);
                    file.$li.appendTo(up.$uploadUL);

                    file.$img = file.$li.find(".uploadimg");
                    file.$previewPic = file.$li.find(".preview-pic");
                    file.$previewTip = file.$li.find(".preview-tip");
                    file.$previewName = file.$li.find(".preview-name");
                    file.$handerBar = file.$li.find(".handle-bar");
                    file.$delQueuedBtn = file.$handerBar.find(".upbtn-del");

                    file.$progress = file.$li.find(".progressing");
                    file.$success = file.$li.find(".successing");
                    file.$error = file.$li.find(".error");

                    file.$delUploadServerBtn = file.$li.find(".upbtn-del-server");
                    file.$inputHidden = file.$li.find('input[name="' + opt.inputHidden.name + '"]');




                    preloadThumb(file, file.$previewPic, function(type) {
                        file.$previewTip.hide();
                        if (type == "error") {
                            file.$previewName.show().children().html(file.name + "(暂不支持该文件预览)");
                        } else {
                            file.$previewPic.show();
                        }
                    }, uploader);

                    toggleHanderBar(up, file, "FilesAdded");
                    //判断如果
                    //删除按钮(队列)
                    file.$delQueuedBtn.on("click", function() {
                        up.removeFile(file);
                    });
                });



            });


            uploader.bind('QueueChanged', function(up) {
                console.group("QueueChanged事件");
                //filter判断一次 这里要在判断一次，因为files上传和删除的时候都会触发这个事件
            });

            //控制打的按钮就要在这个地方，例如重新上传 就会触犯这个函数
            uploader.bind('StateChanged', function(up) {
                //暂时不知道这个的作用

                //执行两次，一个是开始上传的时候
                //然后是上传后FileUploaded 后执行 或者是在Error事件后执行StateChanged，但是两次的执行竟然up.total是一样的
                console.group("StateChanged事件");
                console.dir(up.total);


            });


            //如果上传失败，那么我删除了文件，那么自然会触犯StateChanged 事件，但是在这个事件里面 失败的文件仍然是1
            //但是到refresh的时候，这个failed 就变成了0，所以toggleStartUpload 为什么放这里而不放StateChanged

            uploader.bind('Refresh', function(up) {
                console.group("Refresh事件");
                //QueueChanged都会触发refresh函数，如果有上传的获取是有队列的时候,那么默认的图片就应该隐藏
                if (up.total.uploaded || up.total.failed || (up.files.length - (up.total.uploaded + up.total.failed)) > 0) {
                    up.$noFileDefault.hide();
                } else {
                    up.$noFileDefault.show();
                }
                toggleStartUpload(up, "Refresh");
                toggleBrowseButton(up);
                toggleUploadInfo(up);
            });



            uploader.bind('BeforeUpload', function(up, file) {
                console.group("BeforeUpload事件");
                file.$progress.show();
                file.$error.hide();
                toggleHanderBar(up, file, "BeforeUpload");
                toggleStopUpload(up, "BeforeUpload");
                toggleStartUpload(up, "BeforeUpload");
                toggleUploadInfo(up, "BeforeUpload")



            });

            uploader.bind('UploadFile', function(up, file) {
                console.group("UploadFile事件");
            });






            uploader.bind('UploadProgress', function(up, file) {
                console.group("UploadProgress事件");
                console.dir(file)

                file.$progress.children().css("width", file.percent + "%");
                toggleUploadInfo(up, "UploadProgress");
            });

            uploader.bind('ChunkUploaded', function(up, file, info) {
                console.group("ChunkUploaded事件")
            });

            //文件上传成功才会触发
            uploader.bind('FileUploaded', function(up, file, info) {
                console.group("FileUploaded事件");
                console.dir(info);
                var response = $.parseJSON(info.response);
                console.dir(response);
                console.dir(up.total);
                //服务器上传成功
                if (!!response.OK && response.OK == 1) {
                    file.serverUrl = response.info.path;
                    file.$li.addClass('selected').attr("data-src", response.info.path);
                    file.$success.show();
                    file.$progress.hide().children().css("width", 0);
                    toggleHanderBar(up, file, "FileUploadedSuccess");
                    !!file.$inputHidden.length && file.$inputHidden.val(response.info.path);
                    !!opt.fileUploaded && opt.fileUploaded(up, file)
                    toggleInsertBtn(up);
                } else {
                    //服务器上传失败

                    file.status = plupload.FAILED;
                    file.$error.show();
                    file.$progress.hide().children().css("width", 0);
                    toggleHanderBar(up, file, "FileUploadedFail");
                }

            });




            //固定会触发的
            uploader.bind('UploadComplete', function(up, files) {
                console.group("UploadComplete事件");
                toggleStartUpload(up, "UploadComplete");
                toggleStopUpload(up, "UploadComplete");
                toggleUploadInfo(up, "UploadComplete");
                $.each(files, function(index, file) {
                    file.$progress.hide().children().css('width', 0);
                    if (file.status == plupload.DONE) {
                        file.$success.show();

                        file.$error.hide();
                    } else if (file.status == plupload.FAILED) {
                        //失败的时候

                        file.$error.show();
                        toggleHanderBar(up, file, "UploadComplete");
                    }
                });
                !!opt.uploadComplete && opt.uploadComplete.call(up, files);
            });


            uploader.bind('FilesRemoved', function(up, files) {
                console.group("FilesRemoved事件");
                $.each(files, function(index, file) {
                    file.$li.remove();
                })

            });


            uploader.bind('Destroy', function() {
                console.group("Destroy事件")
            });

            uploader.bind('OptionChanged', function(up, name, value, oldValue) {
                console.group("OptionChanged事件");
                console.dir(up);
            });



            uploader.bind('Error', function(up, err) {
                console.group("Error事件");
                switch (err.code) {
                    case plupload.FILE_EXTENSION_ERROR:
                        details = err.file.name + "文件不符合格式要求！";
                        break;

                    case plupload.FILE_SIZE_ERROR:
                        details = "单个文件大小不能超过" + plupload.formatSize(plupload.parseSize(up.getOption('filters').max_file_size)) + ",<br/>文件(" + err.file.name + ")大小为：" + plupload.formatSize(err.file.size);
                        break;

                    case plupload.FILE_DUPLICATE_ERROR:
                        details = err.file.name + "已经在队列中了！";
                        break;

                    case plupload.HTTP_ERROR:

                        details = "上传的URL出现错误或着文件不存在！";
                        break;

                    case plupload.FILE_COUNT_ERROR:
                        details = "最多只能上传" + (up.getOption('filters').max_file_count || 0) + "个文件";
                        break;

                    case plupload.IMAGE_FORMAT_ERROR:
                        details = _("Image format either wrong or not supported.");
                        break;

                    case plupload.IMAGE_MEMORY_ERROR:
                        details = _("Runtime ran out of available memory.");
                        break;
                }
                layer.msg(details);

            });
            uploader.init();

        },




       

        init: function(editor) {
            var that = this;
            editor.ui.addButton('imagegallery', {
                // The text part of the button (if available) and the tooltip.
                label: '上传图片',
                // The command to execute on click.
                command: 'imagegallery',
                // The button placement in the toolbar (toolbar group name).
                toolbar: 'insert,2'
            });





            //绑定图片双击事件
            editor.on('doubleclick', function(evt) {
                var element = editor.editImg.element = evt.data.element,
                    imgW = "",
                    imgH = "",
                    imgAlt;
                // if (element.is('img') && !element.data('cke-realelement') && !element.isReadOnly()) {
                if (element.is('img') && !element.data('cke-realelement') && !element.isReadOnly()) {
                    if (!editor.editImg.$dialog) {
                        that._editImgRender.call(editor);
                    }
                    if (!element.ratio) {
                        element.ratio = element.$.naturalWidth / element.$.naturalHeight;
                    }
                    console.dir(editor.editImg.element);

                    // console.dir(element.);
                    // console.dir(element.style.width);
                    if (element.getAttribute("width")) {
                        imgW = element.$.clientWidth;
                    }
                    if (element.getAttribute("height")) {
                        imgH = element.$.clientHeight;
                    }

                    if (imgH != element.$naturalWidth || imgW != element.$.naturalHeight) {
                        element.imgLock = false;
                    }

                    imgAlt = element.$.alt;
                    editor.editImg.layerIndex = layer.open({
                        type: 1,
                        shade: false,
                        title: "图片属性",
                        area: '350px',
                        content: editor.editImg.$dialog, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                        success: function(layero, index) {
                            if (element.imgLock || element.imgLock == null) {
                                editor.editImg.$btnLock.removeClass('unlock');
                            } else {
                                editor.editImg.$btnLock.addClass('unlock');
                            }
                            editor.editImg.$inputW.val(imgW);
                            editor.editImg.$inputH.val(imgH);
                            editor.editImg.$inputAlt.val(imgAlt);
                        }
                    });

                    editor.editImg.$btnCancel.off("click").on("click", function(event) {
                        event.preventDefault();
                        layer.close(editor.editImg.layerIndex);
                    });
                    editor.editImg.$btnConfirm.off("click").on("click", function(event) {
                        event.preventDefault();
                        element.setAttributes({
                            width: editor.editImg.$inputW.val(),
                            height: editor.editImg.$inputH.val(),
                            alt: editor.editImg.$inputAlt.val()
                        });

                        layer.close(editor.editImg.layerIndex);

                    });

                    editor.editImg.$btnReset.off("click").on("click", function() {
                        imgW = element.$.naturalWidth;
                        imgH = element.$.naturalHeight;
                        editor.editImg.$inputW.val(imgW);
                        editor.editImg.$inputH.val(imgH);
                    });

                    //锁住和解锁  锁住的时候还要根据图片的比例强制设置宽高
                    editor.editImg.$btnLock.off("click").on("click", function() {
                        imgW = editor.editImg.$inputW.val(),
                            imgH = editor.editImg.$inputH.val();

                        if (element.imgLock || element.imgLock == null) {
                            editor.editImg.$btnLock.addClass('unlock');
                            element.imgLock = false;
                        } else {
                            element.imgLock = true;
                            editor.editImg.$btnLock.removeClass('unlock');
                            if (imgW) {
                                imgH = Math.floor(imgW / element.ratio);
                                editor.editImg.$inputH.val(imgH);
                                editor.editImg.$inputW.val(imgW);
                            } else if (imgH) {
                                imgW = Math.floor(imgH * element.ratio);
                                editor.editImg.$inputW.val(imgW);
                            } else {

                            }
                        }
                    })

                }
            });

            //点击上传图片命令
            editor.addCommand('imagegallery', {
                exec: function(editor) {
                    //判断页面是否纯在弹出框
                    if (!editor.uploaderImg.$dialog) {
                        that._uploadImgInit.call(editor);

                    }
                    editor.uploaderImg.layerIndex = layer.open({
                        type: 1,
                        shade: false,
                        move: ".move-seat",
                        title: false, //不显示标题
                        area: '702px',
                        content: editor.uploaderImg.$dialog, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                        success: function(layero, index) {
                            //ajax 请求
                        },
                        cancel: function(index, layero) {

                        }
                    });
                }
            });
        },


    });


})();